import {
  createContext,
  useContext,
  useEffect,
  useRef,
  useState,
  type PropsWithChildren,
} from "react";
import WSocket from "@/lib/utils/websocket";
import { WS_URL } from "@/lib/constants";
import useOnMounted from "@/lib/hooks/useOnMounted";

type IWebSocketContext = {
  websocket: WSocket;
};

const WebSocketContext = createContext({} as IWebSocketContext);

export function useWebSocket() {
  return useContext(WebSocketContext);
}

// const instance = new WSocket("ws://127.0.0.1:9999/realtime");
const instance = new WSocket(WS_URL);

export default function WebSocketProvider({ children }: PropsWithChildren) {
  const [websocket] = useState(() => {
    return instance;
  });
  const timerRef = useRef<Timer>();

  useOnMounted(() => {
    function ping() {
      timerRef.current = setTimeout(() => {
        websocket.emit("ping");
        ping();
      }, 30000);
    }
    function onPong() {}

    ping();
    websocket.on("pong", onPong);
    return () => {
      websocket.off("pong", onPong);
      clearTimeout(timerRef.current);
    };
  });

  return (
    <WebSocketContext.Provider value={{ websocket }}>
      {children}
    </WebSocketContext.Provider>
  );
}
